﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Rendering;
using BookLink.Data;
using BookLink.Models;

namespace BookLink.Pages.Books
{
    public class CreateModel : PageModel
    {
        private readonly BookLink.Data.BookLinkContext _context;
        private readonly IWebHostEnvironment _environment;

        public CreateModel(BookLink.Data.BookLinkContext context, IWebHostEnvironment environment)
        {
            _context = context;
            this._environment = environment;
        }

        public IActionResult OnGet()
        {
            return Page();
        }

        [BindProperty]
        public Book Book { get; set; }

        [BindProperty]
        public IFormFile BookCover { get; set; }


        // To protect from overposting attacks, see https://aka.ms/RazorPagesCRUD
        public async Task<IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return Page();
            }
            // IHostEnvironment.ContentRootPath获取或设置包含应用程序内容文件的目录的绝对路径
            string localName = $"{Guid.NewGuid()}{Path.GetExtension(BookCover.FileName)}";
            var filePath = Path.Combine(this._environment.WebRootPath, "images", "bookcovers", localName);
            using (var stream = System.IO.File.Create(filePath))
            {
                await BookCover.CopyToAsync(stream);
            }
            Book.ImageUrl = $"/images/bookcovers/{localName}";
            _context.Book.Add(Book);
            await _context.SaveChangesAsync();

            return RedirectToPage("./Index");
        }

    }
}
